/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} code code字段 默认 'code'
 * @param {*} parentCode 父节点字段 默认 'parentCode'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootCode 根Id 默认 0
 */
export function handleTree(data, code, parentCode, children, rootCode) {
	console.log('请求的数据',data)
	console.log('请求的code', code)
	console.log('请求的parentCode',parentCode)
	console.log('请求的子类',children)
	console.log('rootCode',rootCode)
	code = code || 'code'
	parentCode = parentCode || 'parentCode'
	children = children || 'children'
	rootCode = rootCode || 0
	//对源数据深度克隆
	const cloneData = JSON.parse(JSON.stringify(data))
	console.log('克隆的数据',cloneData)
	//循环所有项
	const treeData = cloneData.filter(father => {
		console.log('father',father)
		let branchArr = cloneData.filter(child => {
			// console.log('child',child)
			return father[code] === child[parentCode]
		});
		branchArr.length > 0 ? father.children = branchArr : '';
		//返回第一层
		return father[parentCode] === rootCode;
	});
	return treeData != '' ? treeData : data;
}

/**
 * 格式化日期
 * @param {Object} date  请求参数
 * @param {Object} fmt   格式化标准
 */
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

export function str2Date(dateStr, separator) {
  if (!separator) {
    separator = "-";
  }
  let dateArr = dateStr.split(separator);
  let year = parseInt(dateArr[0]);
  let month;
  //处理月份为04这样的情况
  if (dateArr[1].indexOf("0") == 0) {
    month = parseInt(dateArr[1].substring(1));
  } else {
    month = parseInt(dateArr[1]);
  }
  let day = parseInt(dateArr[2]);
  let date = new Date(year, month - 1, day);
  return date;
}
